﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMOEng.Packets.EnginePackets;
using MMOEng.SubSystems;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using MMOEng.Components;

namespace MMOEng.Managers
{
    public class SubSystemsManager : BaseManager
    {
        public delegate void ComponentRouter(BaseComponent component);
        private Dictionary<string, ComponentRouter> updateCallbacks;

        public RenderSubSystem RenderSystem { get; private set; }

        public SubSystemsManager(MMOGame game) : base("SubSystemsManager",game)
        {
            this.game = game;

            updateCallbacks = new Dictionary<string, ComponentRouter>();
        }

        public override void Update(GameTime gameTime)
        {
            RenderSystem.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            RenderSystem.Draw(gameTime);
        }

        public override void LoadContent()
        {
            //Init systems
            RenderSystem = new RenderSubSystem(game);
            RenderSystem.LoadContent();
        }

        public void RegisterUpdateCallback(string typeName, ComponentRouter callback) 
        {
            if (updateCallbacks.ContainsKey(typeName))
            {
                throw new InvalidOperationException("Component type is already registered with a callback from, " + callback.Target.ToString());
            }
            updateCallbacks.Add(typeName, callback);
        }

        public void RouteCallback(DeltaUpdateP packet)
        {
            if (!updateCallbacks.ContainsKey(packet.ComponentType.FullName))
                throw new InvalidOperationException("Trying to route a component that has no registered callback, " + packet.ComponentType.FullName);

            ComponentRouter r = updateCallbacks[packet.ComponentType.FullName];
            r(packet.Component);
        }
    }
}
